package com.example.cloud.config.web;

import com.example.cloud.interceptor.ClientTokenInterceptor;
import com.example.cloud.interceptor.UserInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by wangtao on 2018/2/2.
 */
@Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
    // 跨域请求
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
                .maxAge(3600)
                .allowCredentials(true);
    }

    // 字符类型转换
    @Override
    public void addFormatters(FormatterRegistry registry) {
    }

    // 配置请求路径拦截
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getUserInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("" +
                        "/checkLogin",
                        "/menus",
                        "/allButtons",
                        "/print/*",
                        "/socket/**",
                        "/skin/type/**",
                        "/patient/findByMedicalNumber");
        super.addInterceptors(registry);
    }

    @Bean
    UserInterceptor getUserInterceptor() {
        return new UserInterceptor();
    }

    @Bean
    ClientTokenInterceptor getClientTokenInterceptor(){
        return new ClientTokenInterceptor();
    }

    // 静态文件映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/templates/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/templates/");
        registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/");
        super.addResourceHandlers(registry);
    }
}
